package com.seed.uaa.web;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import com.seed.core.field.FieldContext;
import com.seed.core.pojo.LoginDTO;
import com.seed.core.pojo.Node;
import com.seed.core.pojo.Subject;
import com.seed.uaa.util.StpKit;
import com.seed.core.pojo.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashMap;
import java.util.List;

@Tag(name = "用户认证授权通用")
@Slf4j
@RestController
public class UaaController {
    private final UaaService uaaService;

    public UaaController(UaaService uaaService) {
        this.uaaService = uaaService;
    }

    @Operation(summary = "登录")
    @PostMapping("login")
    @SaIgnore
    public R<Boolean> login(@RequestBody LoginDTO dto) {
        uaaService.login(dto);
        return R.ok("登录成功");
    }

    @Operation(summary = "退出")
    @GetMapping("logout")
    public R<String> logout() {
        StpKit.logout();
        return R.ok("退出成功");
    }

    @GetMapping("subject")
    public R<Subject> subject() {
        return R.data(uaaService.getSubject());
    }

    @GetMapping("tenant")
    public R<String> tenant() {
        return R.data("未实现");
    }

    @GetMapping("profile")
    public R<Subject> profile() {
        return R.data(uaaService.profile());
    }

    @GetMapping("switchTo")
    public R<Subject> switchTo(String loginId) {
        return R.data(uaaService.switchTo(loginId));
    }

    @GetMapping("endSwitch")
    public R<Boolean> endSwitch() {
        uaaService.endSwitch();
        return R.ok("已结束切换");
    }

    @GetMapping("tenants")
    public R<String> tenants() {
        return R.data("未实现");
    }

    @GetMapping("userTree")
    public R<String> userTree() {
        return R.data("未实现");
    }

    @GetMapping("openSafe")
    public R<String> openSafe(String password) {
        if("123456".equals(password)) {
            StpUtil.openSafe(120);
            return R.ok("");
        }

        return R.error("密码错误");
    }

    @GetMapping("fieldAuths")
    public R<LinkedHashMap<String, String>> fieldAuths() {
        return R.data(FieldContext.fieldAuths());
    }

    @GetMapping("switchable")
    public R<List<Node<Object>>> switchable() {
        return R.data(uaaService.switchable());
    }
}
